package io.renren.modules.noc.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import io.renren.common.utils.MemberExcelHandler;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.noc.entity.NocBusinessLabelEntity;
import io.renren.modules.noc.entity.NocMemberLabelEntity;
import io.renren.modules.noc.service.*;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.noc.entity.NocMemberEntity;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;


/**
 * 
 *
 * @author whc
 * @email hucheng_86@126.com
 * @date 2019-04-03 22:37:46
 */
@RestController
@RequestMapping("noc/nocmember")
public class NocMemberController extends BaseController{
    @Autowired
    private NocMemberService nocMemberService;
    @Autowired
    private NocBusinessService nocBusinessService;
    @Autowired
    private NocMemberLabelService nocMemberLabelService;
    @Autowired
    private NocBeerTicketMemberService nocBeerTicketMemberService;
    @Autowired
    private NocBeerTicketBusinessService nocBeerTicketBusinessService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("noc:nocmember:list")
    public R list(@RequestParam Map<String, Object> params){
        /*Integer defalutTemplateId = this.getDefaultTemplateId();
        if(defalutTemplateId==null){
            return R.error("请先设置默认活动！");
        }*/
        //params.put("templateId",defalutTemplateId);
        PageUtils page = nocMemberService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("noc:nocmember:info")
    public R info(@PathVariable("id") Integer id){
        NocMemberEntity nocMember = nocMemberService.getById(id);

        Map<String,Object> p = new HashMap<>();
        p.put("member_id",id);
        List<NocMemberLabelEntity> labes =  (List<NocMemberLabelEntity>)nocMemberLabelService.listByMap(p);

        Map<String,Object> map = new HashMap<>();
        map.put("nocMember", nocMember);
        map.put("labels",labes);
        return R.ok(map);

        //return R.ok().put("nocMember", nocMember);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("noc:nocmember:save")
    public R save(@RequestBody NocMemberEntity nocMember){
        nocMemberService.save(nocMember);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("noc:nocmember:update")
    public R update(@RequestBody NocMemberEntity nocMember){
        ValidatorUtils.validateEntity(nocMember);
        SysUserEntity user = this.getUser();
        nocMember.setUpdator(user.getRemark());
        nocMember.setUpdateTime(new Date());
        nocMemberService.updateById(nocMember);

        //添加标签
        Map<String,Object> delMap = new HashMap<>();
        delMap.put("member_id",nocMember.getId());
        nocMemberLabelService.removeByMap(delMap);

        String labels = nocMember.getLabelIds();
        if(StringUtils.isNotEmpty(labels)){
            String[]  lbs = labels.split(",");
            for(String lbid:lbs){
                NocMemberLabelEntity labelEntity = new NocMemberLabelEntity();
                labelEntity.setLabelId(Integer.parseInt(lbid));
                labelEntity.setMemberId(nocMember.getId());
                nocMemberLabelService.save(labelEntity);

            }
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("noc:nocmember:delete")
    public R delete(@RequestBody Integer[] ids){
        nocMemberService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    @RequestMapping("/sign")
    public R sign(@RequestBody Integer[] ids){
        //nocMemberService.removeByIds(Arrays.asList(ids));
        List<NocMemberEntity> list = new ArrayList<NocMemberEntity>();
        for(Integer id:ids){
            NocMemberEntity t = new NocMemberEntity();
            t.setId(id);
            t.setIsSign("1");
            list.add(t);
        }
        nocMemberService.updateBatchById(list);
        return R.ok();
    }

    @RequestMapping("/memberCount")
    public R memberCount(String tid,String ly){
        Map<String,Object> params =  new HashMap<>();
        /*Integer defalutTemplateId = this.getDefaultTemplateId();
        if(defalutTemplateId==null){
            return R.error("请先设置默认活动！");
        }
        params.put("tid",defalutTemplateId.toString());*/
        params.put("tid",tid);
        params.put("ly",ly);
        List<Map<String,Object>>  list =  nocMemberService.memberCount(params);
        if(list!=null&&list.size()>0){
            Map<String,Object> map = list.get(0);
            return R.ok(map);
        }
        return R.error();
    }

    /**
     * 发放入场证件
     * @return
     */
    @RequestMapping("/saveCard")
    public R saveCard(@RequestBody NocMemberEntity nocMember){
        Integer templateId = this.getDefaultTemplateId();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("col1",nocMember.getCol1());
        map.put("tid",templateId);
        List<NocMemberEntity> list = (List<NocMemberEntity>)nocMemberService.listByMap(map);
        if(list!=null&&list.size()>0) {
            NocMemberEntity member = list.get(0);
            nocMember.setId(member.getId());
            nocMember.setTid(templateId);
            if(StringUtils.isEmpty(member.getLy())) {
                nocMember.setLy("xianchang");
            }
            nocMemberService.updateById(nocMember);
        }else{
            nocMember.setTid(templateId);
            nocMember.setLy("xianchang");
            nocMemberService.save(nocMember);
        }
        return R.ok();
    }

    @RequestMapping("/userIsExit")
    @ResponseBody
    public R userHasExit(@RequestBody NocMemberEntity nocMember){
        String col20 = nocMember.getCol20();
        String tid = this.getDefaultTemplateId()+"";
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("col20",col20);
        map.put("tid",tid);
        List<NocMemberEntity> list = (List<NocMemberEntity>)nocMemberService.listByMap(map);
        if(list!=null&&list.size()>0){
            return R.ok();
        }
        return R.error();
    }

    @Transactional
    @RequestMapping("/upload")
    @RequiresPermissions("noc:nocmember:upload")
    public R excelImport(@RequestParam("file") MultipartFile file) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        IExcelDataHandler<NocMemberEntity> handler = new MemberExcelHandler();
        // 注意这里对应的是excel的列名。也就是对象上指定的列名。
        handler.setNeedHandlerFields(new String[] { "col1" });
        importParams.setDataHanlder(handler);
        // 需要验证
        importParams.setNeedVerfiy(true);
        String MSG = "";
        try {
            ExcelImportResult<NocMemberEntity> result = ExcelImportUtil.importExcelMore(file.getInputStream(), NocMemberEntity.class, importParams);
            List<NocMemberEntity> successList = result.getList();
            MSG = "成功导入"+successList.size()+"条信息";
            for (NocMemberEntity member :successList){
                if(StringUtils.isNotEmpty(member.getCol1())) {
                    nocMemberService.save(member);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok(MSG);
    }

    @RequestMapping("/getMemberId")
    public R list(@RequestBody String ercode){
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> map = new HashMap<>();
        map.put("ercode",ercode);
        Map<String,Object> result = nocMemberService.getMemberId(map);
        if(result!=null){
            if(!sdf.format(result.get("valid_date")).equals(sdf.format(new Date())) ){
                return R.error(1,"日期不正确"+result.get("valid_date"));
            }
            Map<String,Object> map1 =new HashMap<>();
            map1.put("id",result.get("id"));
            map1.put("type","1");
            map1.put("ticket",result);
            map1.put("isSign",nocBeerTicketMemberService.getIsSign(map).get("is_sign"));
            map1.put("signTime",nocBeerTicketMemberService.getIsSign(map).get("sign_time"));
            return R.ok().put("result",map1);
        }else{
            Map<String,Object> result1 = nocBusinessService.getMemberId(map);
            if(result1!=null){
                if(!sdf.format(result1.get("valid_date")).equals(sdf.format(new Date())) ){
                    return R.error(1,"日期不正确"+result1.get("valid_date"));
                }
            }
            Map<String,Object> map2 =new HashMap<>();
            if(result1==null){
                result1.put("isSign",null);
                result1.put("signTime",null);
                return R.ok().put("result",result1);
            }
            map2.put("id",result1.get("id"));
            map2.put("type",2);
            map2.put("ticket",result1);
            map2.put("isSign",nocBeerTicketBusinessService.getIsSignByCode(map).get("is_sign"));
            map2.put("signTime",nocBeerTicketBusinessService.getIsSignByCode(map).get("sign_time"));
            return R.ok().put("result",map2);
        }

    }
}
